package com.sky.service.impl;


import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Resource
    private WorkspaceService workspaceService;


    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        List<LocalDate> dateList=new ArrayList<>();
        while(begin.isBefore(end)){
            //日期计算
            dateList.add(begin);
            begin=begin.plusDays(1);
        }
        String join = StringUtils.join(dateList, ",");
        turnoverReportVO.setDateList(join);

        List turnoverlist = new ArrayList<>();
        //查询营业额：查询状态为已经完成的订单的金额合计
        for(LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);

            Double turnover = orderMapper.sumByMap(map);
            if(turnover==null){
                turnover=0.0;
            }
            turnoverlist.add(turnover);
        }
        String turnoverString = StringUtils.join(turnoverlist, ",");
        turnoverReportVO.setTurnoverList(turnoverString);


        return turnoverReportVO;
    }


    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        UserReportVO userReportVO = new UserReportVO();
        LocalDate beginCopy1=begin;
        //营业额统计
        List<LocalDate> dateList=new ArrayList<>();
        while(begin.isBefore(end)){
            //日期计算
            dateList.add(begin);
            begin=begin.plusDays(1);
        }
        String join = StringUtils.join(dateList, ",");
        userReportVO.setDateList(join);

        //新增用户数量
        List newUserlist = new ArrayList<>();
        for(LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("beginTime", beginTime);
            map.put("beginTime", endTime);
            int number = userMapper.getByCreateTime(map);
            log.info("{}的新增用户数量是{}",date, number);
            newUserlist.add(number);
        }
        String numberString = StringUtils.join(newUserlist, ",");
        userReportVO.setNewUserList(numberString);

        //总的用户数量
        List totalUserlist = new ArrayList<>();

        int cumulativeTotal = 0;
        for(LocalDate date : dateList){
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            int dailyNew = userMapper.getByTime(endTime);
            cumulativeTotal += dailyNew;
            log.info("{}的累计用户数量是{}", date, cumulativeTotal);
            totalUserlist.add(cumulativeTotal);
        }
        String totalString = StringUtils.join(totalUserlist, ",");
        userReportVO.setTotalUserList(totalString);

        return userReportVO;
    }


    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        OrderReportVO orderReportVO = new OrderReportVO();
        //获取日期序列
        List<LocalDate> dateList=new ArrayList<>();
        while(begin.isBefore(end)){
            //日期计算
            dateList.add(begin);
            begin=begin.plusDays(1);
        }
        String dateString = StringUtils.join(dateList, ",");
        orderReportVO.setDateList(dateString);


        //获取每日订单数
        List<Integer> dateOrderList=new ArrayList<>();
        //获取每日有效订单数
        List<Integer> validOrderList=new ArrayList<>();
        for(LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status",null);
            int orderCount = orderMapper.sumByMapForCount(map);
            dateOrderList.add(orderCount);


            Map validMap = new HashMap();
            validMap.put("beginTime", beginTime);
            validMap.put("endTime", endTime);
            validMap.put("status", Orders.COMPLETED);
            int validOrderCount = orderMapper.sumByMapForCount(validMap);
            validOrderList.add(validOrderCount);
        }


        String dateOrderString = StringUtils.join(dateOrderList, ",");
        String validOrderString = StringUtils.join(validOrderList, ",");

        orderReportVO.setOrderCountList(dateOrderString);
        orderReportVO.setValidOrderCountList(validOrderString);

        //订单总数
        int totalOrderCount=0;
        for(int dateOrder : dateOrderList){
            totalOrderCount+=dateOrder;
        }
        //有效订单数
        int validOrderCount=0;
        for(int dateOrder : validOrderList){
            validOrderCount+=dateOrder;
        }
        //订单完成率
        Double orderCompletionRate=0.0;
        if(validOrderCount>0){
            orderCompletionRate=(double)validOrderCount/(double)totalOrderCount;
        }

        orderReportVO.setValidOrderCount(validOrderCount);
        orderReportVO.setTotalOrderCount(totalOrderCount);
        orderReportVO.setOrderCompletionRate(orderCompletionRate);

        return orderReportVO;
    }


    /**
     * 返回销量前10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        //处理时间上的问题
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        //获取商品名称和销量
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);

        //构建菜品名称和数量列表
        List<String> nameList=new ArrayList<>();
        List<Integer> numberList=new ArrayList<>();

        //遍历  salesTop10
        for(GoodsSalesDTO goodsSalesDTO : salesTop10){
            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getNumber());
        }
        //生成字符串
        String numberString=null;
        String nameString=null;
        nameString = StringUtils.join(nameList, ",");
        numberString = StringUtils.join(numberList, ",");

        salesTop10ReportVO.setNameList(nameString);
        salesTop10ReportVO.setNumberList(numberString);

        return salesTop10ReportVO;
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessDatra(HttpServletResponse response) {
        //查询数据库获取营业数据——查询最近三十天的数据
        //设置时间
        LocalDate dateEnd = LocalDate.now().minusDays(1); //昨天的
        LocalDate dateBegin = LocalDate.now().minusDays(30); //前三十天


        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN),
                LocalDateTime.of(dateEnd, LocalTime.MAX));
        //数据写入excal
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");


        try {
            //基于模板文件创建一个新的excel文件
            XSSFWorkbook excel=new XSSFWorkbook(in);
            //填充数据
            //1。填充生成报表的时间
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充行2 - 修复时间显示错误
            sheet.getRow(1).getCell(1).setCellValue("时间："+dateBegin+"至"+dateEnd);
            //填充行4
            XSSFRow row4 = sheet.getRow(3);
            row4.getCell(2).setCellValue(businessDataVO.getTurnover());
            row4.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row4.getCell(6).setCellValue(businessDataVO.getNewUsers());
            //填充行5 - 修复行索引错误
            XSSFRow row5 = sheet.getRow(4);
            row5.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row5.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据 - 修复日期计算错误
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN),
                        LocalDateTime.of(date, LocalTime.MAX));
                XSSFRow row = sheet.getRow(7 + i);//获得某一行 - 修复行索引
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment;filename=运营数据报表.xlsx");

            //通过输出流导出文件
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            //关闭资源
            outputStream.close();
            excel.close();

        } catch (IOException e) {
            log.error("导出运营数据报表失败", e);
            throw new RuntimeException("导出运营数据报表失败: " + e.getMessage());
        }
    }


}


